
/*
 * Vivien2
 *
 * Copyright (c) 2009 Alexei Samsonov (aka Lancelot).
 * E-mail: alexey.v.samsonov@gmail.com; 
 *
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


/**
 * Authors: Alexei Samsonov (aka Lancelot), alexey.v.samsonov@gmail.com
 */

/**
 * Date: 
 */


module document;


import std.stdio;
import std.path;
import std.file;
import std.string;

import environment;
import parser;
import logger;

/**
 * Class: Document
 *        --------
 * 
 * .print()  — Возвращает клиенту содержимое документа.
 *
 * .fullname — Полный путь к запрашиваемому файлу.
 * .content  — Содержимое документа.
 *
 */
abstract class Document
{
	private char[] _content;
	private char[] _header;


	this(char[] s)
	{
		setContent(s);
		setHeader();
	}




	void print()
	{
		writef("%s", _header);
		writef("%s", _content);

		return 0;
	}
	
	
	void setContent(char[] s)
	{
		_content = s;
	}
	
	void setHeader()
	{
		_header = "Content-type: text/plain; charset=utf8\n\n";
	}
}




class Html : Document
{
	this(char[] s)
	{
		super(s);
	}



	void setContent(char[] s)
	{
		s = autoLoad() ~ s;
		s = parse(s);


		_content = s;
	}
	
	void setHeader()
	{
		_header = "Content-type: text/html; charset=utf8\n\n";
	}



	char[] autoLoad()
	{
		Environment env;
		char[] cdir;		// Curent Directory.
		char[] rdir;		// Root Directory (Document Root).
		char[] diff;
		char[] s;
		char[] fauto;

		env = new Environment();
		cdir = env.get("PATH_TRANSLATED");
		rdir = env.get("DOCUMENT_ROOT");

		if(find(cdir, rdir) == -1)
		{
			Logger log = new Logger();
			log.put("Warning", "\"" ~ rdir ~ "\" is not a root directory of the \"" ~ cdir ~ "\".");
			
			return s;
		}
	


		do
		{
			cdir = getDirName(cdir);
			
			// Автозагружаемый файл.
			fauto = std.path.join(cdir, ".auto.htm");
			
		
			// Если файл не существует.
			if(exists(fauto)==0)
				continue;
			// Это должен быть именно файл, а не каталог.
			if(isfile(fauto)==0)
				continue;


			// Читаем файл в переменную.
			s = cast(char[])read(fauto) ~ s;
		}
		while(cdir != rdir)


		
		return s;
	}
}




class Text : Document
{
	this(char[] s)
	{
		super(s);
	}
}





